import React from 'react'
import PropTypes from 'prop-types'
import QueueAnim from 'rc-queue-anim'
import { Form, Icon, Input, Button } from 'antd'

import styles from './login-form.less'

const FormItem = Form.Item

const LoginForm = ({
  userName,
  phoneNumber,
  loading: loginButtonLoading,
  onLogin,
  form: {
    getFieldsError,
    getFieldDecorator,
    validateFieldsAndScroll
  }
}) => {
  const handleLogin = (e) => {
    e.stopPropagation()
    validateFieldsAndScroll((errors, values) => {
      if (errors) {
        return
      }
      onLogin(`${values.userName}@thoughtworks.com`, values.phoneNumber)
    })
  }

  const hasErrors = (fieldsError) => {
    return Object.keys(fieldsError).some(field => fieldsError[field])
  }

  return (
    <Form className={styles.normal}>
      <QueueAnim>
        <div className={styles.logo} key="1">
          思沃学院线上测试系统
        </div>
        <FormItem hasFeedback key="2">
          {getFieldDecorator('userName', {
            rules: [
              {
                required: true,
                message: '姓名不能为空'
              }
            ],
            initialValue: userName
          })(<Input
            className={styles.fireInput}
            prefix={<Icon type="user" style={{ fontSize: 18 }} />}
            placeholder="姓名"
          />)}
        </FormItem>
        <FormItem hasFeedback key="3">
          {getFieldDecorator('phoneNumber', {
            rules: [
              {
                required: true,
                message: '手机号不能为空'
              }, {
                len: 11,
                message: '必须为11位手机号'
              }, {
                enum: Number,
                message: '必须为11位手机号'
              }
            ],
            initialValue: phoneNumber
          })(<Input
            className={styles.fireInput}
            prefix={<Icon type="lock" style={{ fontSize: 18 }} />}
            type="number"
            placeholder="手机号码"
          />)}
        </FormItem>
        <FormItem hasFeedback className={styles.fireCenter} key="4">
          <Button
            className={styles.button}
            type="primary"
            htmlType="submit"
            size="large"
            loading={loginButtonLoading}
            disabled={hasErrors(getFieldsError())}
            onClick={handleLogin}
          >
            登陆
          </Button>
        </FormItem>
      </QueueAnim>
    </Form>
  )
}

LoginForm.defaultProps = {
  loading: false
}

LoginForm.propTypes = {
  userName: PropTypes.string.isRequired,
  phoneNumber: PropTypes.string.isRequired,
  loading: PropTypes.bool,
  onLogin: PropTypes.func.isRequired
}

export default Form.create()(LoginForm)
